<?php

    class Logger
    {
        private $file;
        private $maxAge = 864000;//10 jours
        
        public function __construct()
        {
            if(defined(LOG_MAX_AGE) && LOG_MAX_AGE)
                $this->maxAge = LOG_MAX_AGE * 86400;
            
            // Nettoie les fichier
            $this->cleanOldLogs();
            
            if(!is_dir(FQ_LOG))
            {
                mkdir(FQ_LOG);
            }
            
            $filename = date("Y-m-d").".log";
            $this->file = fopen(FQ_LOG. "/$filename", 'a');
        }
        public function __destruct()
        {
            fclose($this->file);
        }
        
        public function debug($message)
        {
            $this->write("DEBUG", $message);
        }
        public function info($message)
        {
            $this->write("INFO", $message);
        }
        public function warning($message)
        {
            $this->write("WARNING", $message);
        }
        public function error($message)
        {
            $this->write("ERROR", $message);
        }
        public function fatal($message)
        {
            $this->write("FATAL", $message);
        }

        private function write($header, $message)
        {
            $msg = str_pad(date("H:i:s"), 10, ' ', STR_PAD_RIGHT);
            $msg .= str_pad($header, 10, ' ', STR_PAD_RIGHT);
            $msg .= $message;
            
            fwrite($this->file, "$msg\n");
        }
        
        /**
         * Nettoie les fichiers de log trop vieux
         */
        public function cleanOldLogs()
        {
            
            $file_arr = glob(DIR_LOG."/*.log");
            for($i=0;$i<count($file_arr);$i++)
            {
                $fileName = basename($file_arr[$i]);
                $date = substr($fileName, 0, 10)." 00:00:00";
                $ts = dateTimeToTimestamp($date);
                $age = time() - $ts;
                
                if($age > $this->maxAge)
                {
                    @unlink($file_arr[$i]);
                }
            }
        }
    }

    /**
     * Ecrit une trace DEBUG
     */
    function logDebug($msg)
    {
        $l = new Logger();
        $l->debug($msg);
    }
    /**
     * Ecrit une trace INFO
     */
    function logInfo($msg)
    {
        $l = new Logger();
        $l->info($msg);
    }
    /**
     * Ecrit une trace WARNING
     */
    function logWarning($msg)
    {
        $l = new Logger();
        $l->warning($msg);
    }
    /**
     * Ecrit une trace ERROR
     */
    function logError($msg)
    {
        $l = new Logger();
        $l->error($msg);
    }
    /**
     * Ecrit une trace FATAL
     */
    function logFatal($msg)
    {
        $l = new Logger();
        $l->fatal($msg);
    }
    
?>